package mdm.led.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.led.common.AjaxResponse;
import mdm.led.common.Constant;
import mdm.led.common.LocalConfig;
import mdm.led.entity.three.ExternalSelfItems;
import mdm.led.entity.three.ThreeItem;
import mdm.led.entity.three.ThreeTaskExternal;
import mdm.led.service.ThreeTableService;
import mdm.led.util.ListToString;

/**
 *
 * @author :Monarch丿He
 * @date :2018年12月21日
 * @explain :
 */
@Controller
@RequestMapping(value = "threeTaskExternalApp")
@Api(description = "外部联系人任务")
public class ThreeTaskExternalAppController {

	private Logger logger = Logger.getLogger(ThreeTaskExternalAppController.class);
	@Autowired
	private ThreeTableService threeTableService;
	@Autowired
	protected LocalConfig localConfig;

	@ApiOperation(value = "添加外部任务", notes = "入参:<br>selfTaskID:自查任务ID")
	@RequestMapping(value = "addTaskExternal", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResponse addTaskExternal(@RequestParam("selfTaskID") Integer selfTaskID) {
		logger.info("\n======== 添加外部任务  ========\n");
		boolean flag = false;
		try {
			Integer addTaskExternal = threeTableService.addTaskExternal(selfTaskID);

			flag = (addTaskExternal > 0) ? true : false;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, (flag == true ? "成功" : "失败"));
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, (flag == true ? "成功" : "失败"));
		}
	}

	@ApiOperation(value = "查询外部任务集合", notes = "入参:<br>userID : 当前用户ID")
	@RequestMapping(value = "findTaskExternal", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse findTaskExternal(@RequestParam("userID") Integer userID) {

		logger.info("\n======== 查询外部任务集合  ========\n");
		boolean flag = false;
		List<ThreeTaskExternal> findTaskExternal = null;
		try {
			findTaskExternal = threeTableService.findTaskExternal(userID);
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		logger.info("\n======== 结果值 : \n" + JSON.toJSONString(findTaskExternal) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, findTaskExternal);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}
	}

	@ApiOperation(value = "根据外部任务ID 和自查ID 查询所有检查项", notes = "入参:<br>taskID: 任务ID<br>selfTaskID: 自查详情ID")
	@RequestMapping(value = "findTaskExternalByID", method = RequestMethod.GET)
	@ResponseBody
	public AjaxResponse findTaskExternalByID(Integer taskID, Integer selfTaskID) {
		logger.info("\n======== 根据外部任务ID 和自查ID 查询所有检查项  ========\n");
		boolean flag = false;
		ExternalSelfItems findTaskExternalByID = null;
		try {
			findTaskExternalByID = threeTableService.findTaskExternalByID(taskID, selfTaskID);
			flag = true;
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		logger.info("\n======== 结果值 : \n" + JSON.toJSONString(findTaskExternalByID) + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, findTaskExternalByID);
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, "异常");
		}
	}

	@ApiOperation(value = "修改外部任务")
	@RequestMapping(value = "updateTaskExternal", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResponse updateTaskExternal(HttpServletRequest request) {
		logger.info("\n======== 修改外部任务  ========\n");
		// 存放图片的路径
		String imgPath = localConfig.getPicture_upload();
		boolean flag = false;
		try {
			ExternalSelfItems exteritems = null;
			// JSON 字符串
			String body = request.getParameter("body");
			body = body.replaceAll("null", "");
			logger.info("\n------------param:" + body);
			// json 转对象
			exteritems = JSON.parseObject(body, ExternalSelfItems.class);
			// 1 获取检查项==
			List<ThreeItem> items = exteritems.getItems();

			if (items != null) {
				// 获取数据实体
				Collection<Part> parts = request.getParts();
				// 文件后缀
				String suffix = "";
				// 文件名
				String fileName = "";
				// 图片集合
				List<String> list = new ArrayList<>();
				int i = 0;
				Random random = new Random();
				// 循环解析
				for (Part part : parts) {
					if (!part.getName().toString().equals("body")) {
						// 获取 范围内随机数
						int nextInt = random.nextInt(999999 - 100000) + 100000;
						i++;
						fileName = part.getName();
						// 前缀 ---- 检查项 ID
						String prefix = fileName.substring(0, fileName.indexOf("-") + 1);
						suffix = fileName.substring(fileName.lastIndexOf("."));
						// 写入文件到 指定文件夹 imgPath
						String file = prefix + String.valueOf(System.currentTimeMillis()) + String.valueOf(nextInt) + i
								+ suffix;
						// 添加到 文件集合
						list.add(file);
						// 写入文件
						part.write(imgPath + file);
					}
				}

				// 2 解析图片==
				List<String> fileStr = null;
				if (items.size() > 0 && list.size() > 0) {
					// 循环分类存入图片
					for (ThreeItem item : items) {
						fileStr = new ArrayList<>();
						for (String str : list) {
							// 前缀 ---- 检查项 ID
							String prefix = str.substring(0, str.indexOf("-"));
							if (Integer.parseInt(prefix) == item.getItemId()) {
								fileStr.add(str);
							}
						}
						if (fileStr.size() > 0) {
							String imgsStr = ListToString.stringListToString(fileStr, ",");
							item.setContent(imgsStr);
						}
					}
				}
			}
			flag = threeTableService.updateTaskExternal(exteritems);

		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}
		logger.info("\n======== 结果 : " + (flag == true ? "成功" : "失败") + " ========\n");
		if (flag) {
			return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, (flag == true ? "成功" : "失败"));
		} else {
			return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, (flag == true ? "成功" : "失败"));
		}
	}
}
